<?php

/*------------------------------------------------
*
*   Explay Engine Content Management System.
*   Copyright © 2008 Golovdinov Alexander.
*
*-------------------------------------------------
*
*   Official site: wwww.alex-home.spb.ru/explay.html
*   Contact e-mail: golovdinov@gmail.com
*
*   GNU General Public License original source:
*   http://www.gnu.org/licenses/gpl-3.0.html
*
------------------------------------------------*/

if (!is_registered ()) exit;
if (!isset($_POST['user_id']) || !isset($_POST['value'])) exit;

$id = intval($_POST['user_id']);

$get_user = $db->query ("SELECT user_karma, karma_votes, voters FROM ".DB_PEREFIX."_users WHERE user_id = $id");
if ($db->num_rows($get_user) != 1) exit;
list($karma, $votes_, $voters) = $db->fetch_row($get_user);

if (my_karma () < 0 && !is_admin ()) exit;

$votes = explode (',', $GLOBAL_USER['my_votes']);
foreach ($votes as $v) {
	if (trim($v) == $id) exit('уже голосовал');
}


// Изменяем карму и кол-во проголовавших
$unit = 1;

if (is_admin())
	$unit = 2;
elseif (my_karma () > 80)
	$unit = 4;
elseif (my_karma () > 50)
	$unit = 3;
elseif (my_karma () > 20)
	$unit = 2;

$unit = (float) $unit.'.'.mt_rand(0,50);

if ($unit > 5) $unit = 4;


if ($_POST['value'] == 1)
	$new = $karma[0] + $unit;
elseif ($_POST['value'] == 2)
	$new = $karma[0] - $unit;
else
	exit;
	

$votes_++;
$new = number_format($new, 2, ',', '');


// Именяем проголосовавших

($voters == '')
	? $new_voters = $GLOBAL_USER['user_id'].'='.$_POST['value']
	: $new_voters = $voters.','.$GLOBAL_USER['user_id'].'='.$_POST['value'];



// Обновляем "объект"
$db->query("UPDATE ".DB_PEREFIX."_users SET user_karma = '$new', karma_votes = '$votes_', voters = '$new_voters' WHERE user_id = $id");
	


// Обновляем "субъект"
($GLOBAL_USER['my_votes'] == '')
	? $new_votes = $id
	: $new_votes = $GLOBAL_USER['my_votes'].','.$id;
	
$db->query("UPDATE ".DB_PEREFIX."_users SET my_votes = '$new_votes' WHERE user_id = ".$GLOBAL_USER['user_id']);


// Выводим карму
Templater::load ('users/karma.tpl');
Templater::set_var ('karma', $new);
Templater::set_var ('votes', $votes_);

if ($new >= 0)
	print Templater::display_part ('cant_good');
else
	print Templater::display_part ('cant_bad');